/**
 @Name：common 工具类
 @Author：xiaolai
 @Site：http://www.9dyun.cn
 @License：9DIAN

 */
var common = (function () {
    var ACCESS_TOKEN_KEY = "sop_admin_access_token";
    var USER_INFO_KEY = "dian_user_info";
    var ENT_INFO_KEY = "dian_ent_info";
    var BUS_STYLE_INFO_KEY = "bus_style_info";
    // 接口URL,更改此处即可
    var url = SopConfig.url();
    var URI_CHAR = '/';
    var params = {};


    (function () {
        var aPairs, aTmp;
        var queryString = window.location.search.toString();
        queryString = queryString.substring(1, queryString.length); //remove   "?"
        aPairs = queryString.split("&");
        for (var i = 0; i < aPairs.length; i++) {
            aTmp = aPairs[i].split("=");
            params[aTmp[0]] = decodeURIComponent(aTmp[1]);
        }
    })();

    function formatUri(uri) {
        if (uri.substring(0, 1) !== URI_CHAR) {
            uri = URI_CHAR + uri;
        }
        if (uri.substring(uri.length - 1) !== URI_CHAR) {
            //uri = uri + URI_CHAR;
        }
        return uri;
    }
    function ajax(uri, params,type, successCallback,errorCallback,btn){
        layer.load(1, {shade: 0.1});
        uri = url+formatUri(uri)
        $.ajax({
            type : type,//向后台请求的方式，有post，get两种方法
            url : uri,//url填写的是请求的路径
           // cache : false,//缓存是否打开
            data : $.isEmptyObject(params)?null:JSON.stringify(params),
            contentType : 'application/json',//添加这句话
            dataType : "json",
            success : function(resp) {//请求的返回成功的方法
                layer.close(layer.index);
                var code = resp.code
                if (code === -100 || code === 401 || code === 21) { // 未登录
                    common.util.logout();
                    return
                }
                if (code === 0) { // 成功
                    successCallback(resp)
                } else {
                    if(errorCallback){
                        errorCallback(resp);
                    }else{
                        common.util.error(resp.msg,{icon:5,shift:6})
                    }
                }
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {//请求的失败的返回的方法
                layer.close(layer.index);
                if(btn)$(this).prop('disabled', false);
                if(errorCallback){
                    errorCallback(resp);
                }else{
                    common.util.error('系统错误',{icon:5,shift:6})
                }
            }
        });
    }
    return {
        constant:{
            getEchartsConfig:function(){
                return {
                    path: '{/}https://cdn.bootcss.com/echarts/4.2.1-rc1/echarts.min',
                    then: function () {
                        // then 回调非必须的，一般用来引入一些对应的css或者用来返回layui[modelName] = 被引入的插件的某些特殊的变量可以在then回调返回相关的值
                        return window.echarts;
                    }
                };
            },
            getZtreeConfig:function(){
                return {
                    path: '{/}https://cdn.bootcss.com/zTree.v3/3.5.30/js/jquery.ztree.all',
                    then: function () {
                        //layui.link('https://cdn.bootcss.com/zTree.v3/3.5.30/css/zTreeStyle/zTreeStyle.css', null, 'ztree');
                        layui.link(layui.cache.base +'/ztree/metroStyle/metroStyle.css', null, 'ztree');
                    }
                };
            },
            getZtreeExhideConfig:function(){
              return {
                  path: '{/}https://cdn.bootcss.com/zTree.v3/3.5.30/js/jquery.ztree.exhide.min',
                  extend: ['ztree']
              };
            }

        },
        util:{
            getTableHeight:function(url,param){
                var formHeight=0;
                var navHeight=0;
                var height=4;
                if($(".layui-form").length>0){
                    formHeight=$(".layui-form")[0].getBoundingClientRect().height;
                }
                if($(".x-nav").length>0){
                    navHeight=$(".x-nav")[0].getBoundingClientRect().height;
                }
               return  formHeight+navHeight+height;
            },

            initPage:function(re){
                common.util.windowMode(parent.window.busStyle==1)
            },
            windowMode:function(re,url){
                if(re||common.util.getBusStyle()){
                    $(".x-nav").hide();
                    $("i.layui-extend-fanhui").parent().removeAttr("onclick");
                    $("i.layui-extend-fanhui").parent().html("<i  class=\"layui-icon layui-icon-close-fill\"></i>关闭")
                    $("i.layui-icon-close-fill").parent().click(function(e){
                       // parent.searchTable();
                        common.util.returnWindow(url,{busStyle:1});
                    });
                }
            },
            tableCos:function(conf){
                var cols=common.util.getSession(common.util.getPathName());
                if(cols){
                    try{
                        if(conf.cols.length>1){
                            return conf;
                        }
                        var map = [];
                        var newHideCols=[];
                        var seCols=eval("("+JSON.parse(cols)+")");
                        conf.cols[0].forEach(function (v,i) {
                            if(v.type){
                                v.seq=i;
                                map.push(v);
                                return false;
                            }

                            var obj= seCols.find(function (v1) {
                                if(v1.field==v.field){
                                    return v1;
                                }
                            });
                            if(obj){
                                if(obj.width)v.width=parseInt(obj.width);
                                if(obj.hide)v.hide=true;
                                v.seq=seCols.indexOf(obj)+2;
                                map.push(v);
                            }else{
                                newHideCols.push(v);
                            }
                        },this);
                        map.sort(function(a,b){
                            return a.seq-b.seq;
                        })
                        conf.cols[0]=map.concat(newHideCols);
                    }catch (e) {
                        console.error(e)
                    }
                }

                return conf;
            },
            toFixed:function(val,fixed) {
                return val.toFixed(fixed||4);
            },
            getRootPath:function(){
                    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
                    var curWwwPath=window.document.location.href;
                    //获取主机地址之后的目录，如： /uimcardprj/share/meun.jsp
                    var pathName=window.document.location.pathname;
                    var pos=curWwwPath.indexOf(pathName);
                    //获取主机地址，如： http://localhost:8083
                    var localhostPaht=curWwwPath.substring(0,pos);
                    //获取带"/"的项目名，如：/uimcardprj
                    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
                    return(localhostPaht+projectName);
            },
            getPathName:function(){
                var pathName=window.document.location.pathname;
                return pathName;

            },
            load:function(){
                window.top.layer.load(0, { shade: [0.1,'#fff']}); //0代表加载的风格，支持0-2
            },
            close:function(){
                window.top.layer.close(window.top.layer.index);
            },
            error:function(msg){
                layui.use('notice', function(){
                    var notice = layui.notice;
                    notice.error(msg);
                });
                //layer.msg(msg,{icon:5,shift:6});
            },
            success:function(msg){
                layui.use('notice', function(){
                    var notice = layui.notice;
                    notice.success(msg);
                });
                //layer.msg(msg,{icon:5,shift:6});
            },
            info:function(msg) {
                layui.use('notice', function(){
                    var notice = layui.notice;
                    notice.info(msg);
                });
                //layer.msg(msg);
            },
            tips:function(msg,id) {
                layer.tips(msg, id);
            },
            alert:function(msg,callBack) {
                layer.alert(msg,callBack)
            },confirm:function(msg,callBack1,callBack2,_btn){
                var btn=_btn||{btn: ['确认','取消']}
                layer.confirm(msg,btn, callBack1, callBack2);
            },
            setConfig:function (key,accessToken) {
                sessionStorage.setItem(key,accessToken);
            }
            , getConfig: function (key) {
                return common.util.getSession(key) || '';
            },
            setDist:function (key,accessToken) {
                common.util.setSession(key,accessToken);
            }
            , getDist: function (key) {
                return JSON.parse(common.util.getSession(key)) || '';
            },
            setSession:function (key,accessToken) {
                sessionStorage.setItem(key,accessToken);
            }
            , getSession: function (key) {
                return sessionStorage.getItem(key) || '';
            },
             setAccessToken:function (accessToken) {
                 common.util.setSession(ACCESS_TOKEN_KEY,accessToken);
            }
            , getAccessToken: function () {
                return  common.util.getSession(ACCESS_TOKEN_KEY) || '';
            },setBusStyle:function (value) {
                common.util.setSession(BUS_STYLE_INFO_KEY,value);
            }
            , getBusStyle: function () {
                return (common.util.getSession(BUS_STYLE_INFO_KEY) || '1')==="1";
            },setEntInfo:function (entInfo) {
                common.util.setSession(ENT_INFO_KEY,entInfo);
            }
            , getEntInfo: function () {
                return JSON.parse(common.util.getSession(ENT_INFO_KEY)) || '';
            },
             getEntType:function () {
                return  common.util.getEntInfo().entType;
            }
            , setUserInfo:function (userInfo) {
                common.util.setSession(USER_INFO_KEY,userInfo);
            }
            , getUserInfo: function () {
                return JSON.parse(common.util.getSession(USER_INFO_KEY)) || '';
            }
            ,
            getUserTenantId:function () {
               return  common.util.getUserInfo().tenantId;
            }
            , getUserId:function () {
                return  common.util.getUserInfo().id;
            }
            , getUserName:function () {
                return  common.util.getUserInfo().userName;
            }
            , logout2: function () {
                sessionStorage.removeItem(ACCESS_TOKEN_KEY);
                top.location.href ='/pages/login.html';
            }
            , logout: function () {
                layer.msg('会话过期,请登陆', {
                    icon: 2,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                }, function(){
                    common.util.logout2()
                });
            }
            , getUrl: function () {
                return url;
            }
            , createUrl: function (uri, params) {
                if (!uri) {
                    throw new Error('uri不能为空');
                }
                return url + formatUri(uri) + (params ? '?'+$.param(params) : '');
            }
            , getParam: function (paramName) {
                return params[paramName];
            },
            openWindow:function(_config){
                if(common.util.getBusStyle()||_config.busStyle==1){
                    var config={
                        type: 2,
                        area: [($(window).width()*0.5)+'px', ($(window).height() *0.6)+'px'],
                        shadeClose: false,
                        closeBtn:1,
                        success: $.noop,
                        cancel:$.noop,
                        end:$.noop
                    }
                    return parent.layer.open($.extend(config,_config));
                } else{
                    var path=_config.content.substring(0,_config.content.lastIndexOf('/')+1);
                    if(_config.content.indexOf(path)>=0){
                        _config.content = _config.content.replace(path,'');
                    }
                    location.href = _config.content;
                }

            },
            returnWindow:function(url,param){
                layer.close(layer.index);
                parent.layer.close(parent.layer.index);
                if(common.util.getBusStyle()||param.busStyle==1){
                    var contentWindow=parent.window.frames[parent.getIndexTab()];
                    if(contentWindow&&contentWindow.formCallBack){
                        contentWindow.formCallBack(param);
                    }
                }else{
                    location.href = url;
                }
            },
            /*
            returnWindowsFun:function(url,param){
                common.util.callParentFun(param)
            },
            callParentFun:function(param){
                layer.close(layer.index);
                parent.layer.close(parent.layer.index);
                if(common.util.getBusStyle()){
                    var contentWindow=parent.window.frames[parent.getIndexTab()];
                    if(contentWindow&&contentWindow.formCallBack){
                        contentWindow.formCallBack(param);
                    }
                }else{
                    if(parent.window.frames[0].formCallBack)
                        parent.window.frames[0].formCallBack(param);
                }

            },*/
            exportX:function(url,param){
                param=param||{};
                param['token']=common.util.getAccessToken();
                location.href = common.util.createUrl(url,param);
            },
            exportWindows:function(url,param){
                  param=$.extend(param,{pages:1,limit:10})
                   var content= [
                       '<div class="x-body" id="exportProp">',
                    '    <form  id="exportForm" class="layui-form" action=""   style="width: 350px;padding-top: 10px">',
                    '        <div class="layui-form-item">',
                    '            <div class="layui-input-block">',
                    '                <input type="radio" name="exprotType" value="0" title="导出本页数据" checked>',
                    '                <input type="radio" name="exprotType" value="1" title="导出所有数据" >',
                    '            </div>',
                    '        </div>',
                    '    </form>',
                    '</div>'
                   ].join("");
                layer.open({
                    type: 1,
                    area: ['400px', '160px'],
                    fix: false, //不固定
                    shadeClose: true,
                    shade:0.4,
                    title: '数据导出',
                    content: content,
                    btn: ['导出', '关闭'],
                    success:function(){
                        layui.define(['form'], function (exports) {
                            var form = layui.form;
                            form.render();
                        })
                    },
                    yes: function(index, layero){
                        layui.define(['form'], function (exports) {
                            var exportForm = layui.Form('exportForm');
                            param=param||{};
                            param['exprotType']=exportForm.getData().exprotType;
                            common.util.exportX(url,param)
                            layer.close(index);
                        })

                    }
                    ,btn2: function(){
                        layer.closeAll();
                    }
                });
            },
            isNumeric:function(value,_type){
                var type=_type||1;
                var r;

                if(type==1){
                    //正整数包括0
                    r = new RegExp("^[0-9]*$");
                }else if(type==2){
                    //大于0的正整数
                    r = new RegExp("^\\+?[1-9][0-9]*$");
                }else if(type==3){
                    //正浮点数
                    r = new RegExp("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$");
                }
                return r.test(value);
            },
            cookie:{
                setCookie:function(name, value, expires, path, domain, secure) {
                    if(typeof is_remember!="undefined")
                        return false;
                    var today = new Date();
                    today.setTime( today.getTime() );
                    var expires_date = new Date( today.getTime() + (expires) );
                    document.cookie= name + "=" + escape(value) +
                        ((expires) ? "; expires=" + expires_date.toGMTString() : "") +
                        ((path) ? "; path=" + path : "") +
                        ((domain) ? "; domain=" + domain : "") +
                        ((secure) ? "; secure" : "");
                },
                getCookie:function(name) {
                    var dc = document.cookie;
                    var prefix = name + "=";
                    var begin = dc.indexOf("; " + prefix);
                    if (begin == -1) {
                        begin = dc.indexOf(prefix);
                        if (begin != 0) return null;
                    } else {
                        begin += 2;
                    }
                    var end = document.cookie.indexOf(";", begin);
                    if (end == -1) {
                        end = dc.length;
                    }
                    return unescape(dc.substring(begin + prefix.length, end));
                },
                deleteCookie:function(name, path, domain) {
                    if (getCookie(name)) {
                        document.cookie = name + "=" +
                            ((path) ? "; path=" + path : "") +
                            ((domain) ? "; domain=" + domain : "") +
                            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
                    }
                }
            },
            getDate:function(){
                var date = new Date();
                var seperator1 = "-";
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                var strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                var currentdate = year + seperator1 + month + seperator1 + strDate;
                return currentdate;
            },disabledBtn:function (dst) {
                $("#"+dst).addClass('layui-btn-disabled').attr("disabled","disabled");
            },disabledBtnInput:function(ignore){
                $("input,button:not(#returnBtn),textarea select").removeClass("red").addClass('layui-btn-disabled').attr("disabled","disabled");
                //$("input,button:not("+ignore+")")
                //$("input button")
            }
        },
        ajax:{
            post: function (uri, params, successCallback,errorCallback) {
                ajax(uri,params,'post',successCallback,errorCallback);
            },
            get: function (uri, params, successCallback,errorCallback) {
                ajax(uri,params,'get',successCallback,errorCallback);
            }

        },
        from:{
            serializeObject: function (id) {
                var field = {};
                var fieldElem = $(id).find('input,select,textarea'); //获取所有表单域
                var nameIndex = {}; //数组 name 索引
                $.each(fieldElem, function (_, item) {
                    item.name = (item.name || '').replace(/^\s*|\s*&/, '');

                    if (!item.name) return;

                    //用于支持数组 name
                    if (/^.*\[\]$/.test(item.name)) {
                        var key = item.name.match(/^(.*)\[\]$/g)[0];
                        nameIndex[key] = nameIndex[key] | 0;
                        item.name = item.name.replace(/^(.*)\[\]$/, '$1[' + (nameIndex[key]++) + ']');
                    }

                    if (/^checkbox|radio$/.test(item.type) && !item.checked) return;
                    field[item.name] = item.value;
                });
                return field;
            }
        },
        auth:{
            init:function(pres,roles)
            {
                if(pres&&pres.length>0){
                    for (var i = 0; i < pres.length; i++) {
                        sessionStorage.setItem("pre-"+pres[i],"1");
                    }
                }
                if(roles&&roles.length>0) {
                    for (var i = 0; i < roles.length; i++) {
                        sessionStorage.setItem("role-"+roles[i], "1");
                    }
                }
            },
            get: function(perName)
            {
                return  sessionStorage.getItem(perName)||'';
            },
            hasRole :function(roleName)
            {
                return common.auth.get("role-"+roleName)=="1"?true:false;
            },
            hasPermission : function(preName)
            {
                if(common.auth.get("pre-"+preName)=="1"){
                    return true;
                }else{
                    window.top.common.util.error('对不起,您无此操作权限,请联系管理员')
                    return false;
                }

            },
            _hasRole:function()
            {
                $('[hasRole]').each(function () {
                    if(common.auth.get("role-"+$(this).attr("hasRole"))!="1"){
                        $(this).remove();
                    }
                })
            },_hasPermission:function(){
                $('[hasPermission]').each(function () {
                    if(common.auth.get("pre-"+$(this).attr("hasPermission"))!="1"){
                        $(this).remove();
                    }
                });
            }
        },
        dist:{

            get: function (distName) {
                return JSON.parse(common.util.getSession(distName)||''||'{}')
            },
            getValue: function (distName,key) {
                var enumObj=common.dist.get(distName);
                var value='';
                if(enumObj){
                    $.each(enumObj,function () {
                        if(this.key==key){
                            value=this.value;
                            return false;
                        }
                    })
                }
                return value;
            },
            getKey: function (distName,value) {
                var enumObj=common.dist.get(distName);
                var key='';
                if(enumObj){
                    $.each(enumObj,function () {
                        if(this.value==value){
                            key=this.key;
                            return false;
                        }
                    })
                }
                return key;
            }

        },
        layui:{

            table: {
                readOnly:function(tableConfig){
                    var tableCols=[];
                    tableConfig.cols.forEach(function (val,index,arr) {
                      val.forEach(function(val2,index,arr){
                          if(val2.edit){
                              val2.edit=false;
                          }
                      })
                    })
                    return tableConfig;
                },
                verify:function(table,tableConfig){
                        var mustList=[];
                        var checkResult=true;
                        $.each(tableConfig.cols[0],function () {
                            if(this.must&&this.edit){
                                this.verifyEdit=this.verifyEdit||function(obj,index){
                                    var exp=obj[this.field];
                                    if(exp && typeof exp != "undefined"){
                                        return false;
                                    }
                                    if(exp===0)return false;
                                    return true;
                                }
                                mustList.push(this);
                            }
                        })
                        var index=1;
                        $.each(table.cache[tableConfig.id],function () {
                            var that=this;
                            $.each(mustList,function () {
                                if(this.verifyEdit(that,index)){
                                    var verifyMsg=this.verifyMsg||"第{0}行  {1}不能为空"
                                    $('div[lay-id='+tableConfig.id+']').find('.layui-table-main .layui-table tr[data-index='+(index-1)+'] [data-field='+this.field+']').trigger('click');
                                    checkResult=false;
                                    common.util.error(verifyMsg.format(index,this.title))
                                    return false;
                                }
                            })
                            index++;
                            if(!checkResult)  return false;
                        });
                        return checkResult;
                },
                get:function(dst){
                    var _table=new HYtablelist(dst)
                        _table.romance();
                    return _table;
                },
                addData:function(_config){
                    var opt=$.extend({
                        tableObj:"",
                        fromPk:"",
                        datas:[],
                        done:$.done
                    },_config);
                    var config = opt.tableObj.config;
                    opt.table.reload(config.id, $.extend(true, {
                        // 更新数据
                        data: _config.datas,
                    }, config.page ? {
                        // 一般新增都是加到最后，所以始终打开最后一页
                        page: {
                            curr: Math.ceil(_config.dataTemp.length / config.page.limit)
                        }
                    } : {}));
                },
                addRows:function(_config){
                    var opt=$.extend({
                        tableObj:"",
                        fromPk:"",
                        datas:[],
                        done:function(){}
                    },_config);
                    if(!opt.table){
                        layui.hint().error('table不能为空');
                        return;
                    }
                    if(!opt.tableObj){
                        layui.hint().error('config.tableObj不能为空');
                        return;
                    }
                    var config = opt.tableObj.config;

                    var dataTemp =opt.table.cache[config.id]||[];
                    opt.datas.forEach(function (data) {
                        var index=-1;
                        if(dataTemp.length>0){
                            index=dataTemp.findIndex(function (value) {
                           // return value[opt.fromPk]==data[opt.fromPk]
                        });
                        }
                        if(index>=0){
                            dataTemp[index]=opt.done(dataTemp[index],data);
                        }else{
                            dataTemp.push(data);
                        }
                    })
                    opt.table.reload(config.id, $.extend(true, {
                        // 更新数据
                        data: dataTemp,
                    }, config.page ? {
                        // 一般新增都是加到最后，所以始终打开最后一页
                        page: {
                            curr: Math.ceil(dataTemp.length / config.page.limit)
                        }
                    } : {}));
                },
                config:function(){
                    layui.define(['tablePlug'], function () {
                        var tablePlug=layui.tablePlug;
                        tablePlug.smartReload.enable(true);
                    })
                        return {
                            // loading: true
                             page: true
                           // , height: parent.window.busStyle==1?'full-42':'full-80'
                            ,height: 'full-'+common.util.getTableHeight()
                            , colFilterRecord: true
                            , method:'GET'
                            ,primaryKey: 'id'
                            , defaultToolbar: false
                            , smartReloadModel: true
                            , request: common.layui.table.tableRequest
                            , parseData: common.layui.table.tableParseData
                            , cellMinWidth: 120 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                            ,done: function () {
                                var that=this;
                                layui.define(['soulTable'], function () {
                                    var soulTable=layui.soulTable;
                                    soulTable.render(that)
                                });
                                $("td[data-edit] div").css({"background-color":"#FFF","border":" 1px solid rgb(24, 159, 146)"});
                            }
                        }
                },
                tableRequest: function (res) {
                    return {
                        pageName: 'page' //页码的参数名称，默认：page
                        , limitName: 'limit' //每页数据量的参数名，默认：limit
                    };
                },
                tableParseData: function (res) {
                    if (res.code === 0) {
                        return {
                            "code": res.code, //解析接口状态
                            "msg": res.msg, //解析提示文本
                            "count": res.page.totalCount, //解析数据长度
                            "data": res.page.list //解析数据列表
                        };
                    } else if (res.code === 401) {
                        common.util.logout()
                        return {};
                    } else {
                        common.util.error('系统错误:'+res.msg,{icon:5,shift:6})
                        return {};
                    }
                }
            }
        }
    }
})();

(function () {
    //alert('到common')
    common.util.windowMode(parent.window.busStyle==1)
    //设置AJAX的全局默认选项
    var settings={
        headers: { // 默认添加请求头
            token: common.util.getAccessToken()
        }
    }
    jQuery.ajaxSetup( settings );

    //初始化权限按钮
    common.auth._hasPermission();
    common.auth._hasRole();

    //表格单击行选择中
    $('body').on('click', '.layui-table-body tr', function(e){
        $('.layui-form-checkbox', this).click();
    })
    $('body').on('click', '.layui-form-checkbox', function(e){
        e.stopPropagation();
    })
    String.prototype.format = function(args) {
        if (arguments.length > 0) {
            var result = this;
            if (arguments.length == 1 && typeof(args) == "object") {
                for (var key in args) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            } else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] == undefined) {
                        return "";
                    } else {
                        var reg = new RegExp("({[" + i + "]})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }
            }
            return result;
        } else {
            return this;
        }
    }
    // 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
    Date.prototype.format = function(fmt)
    { //author: meizz
        var o = {
            "M+" : this.getMonth()+1,                 //月份
            "d+" : this.getDate(),                    //日
            "h+" : this.getHours(),                   //小时
            "m+" : this.getMinutes(),                 //分
            "s+" : this.getSeconds(),                 //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt))
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)
            if(new RegExp("("+ k +")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        return fmt;
    }
})();
